import util from "../libs/util";

let loadDom = null;

/**
 * 判断是否存在
 * @param {Object} value
 */
function isDefine(value) {
    if (value == null || value == "" || value == "undefined" || value == undefined || value == "null" || value == "(null)" || value == 'NULL' || typeof (value) == 'undefined') {
        return false;
    } else {
        value = value + "";
        value = value.replace(/\s/g, "");
        if (value == "") {
            return false;
        }
        return true;
    }
}


/**
 * 时间戳格式化函数
 * @param  {string} format    格式
 * @param  {int}    timestamp 要格式化的时间 默认为当前时间
 * @return {string}           格式化的时间字符串
 */
function date(format, timestamp) {
    console.log(timestamp);
    var a, jsdate = ((timestamp) ? new Date(timestamp * 1000) : new Date());
    var pad = function (n, c) {
        n = n + "";
        if (n.length < c) {
            var i = c - n.length;
            var v = '';
            for (var j = 0; j < i; j++) {
                v += '0';
            }
            return v + n;
        } else {
            return n;
        }
    };
    var txt_weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    var txt_ordin = {"1": "st", "2": "nd", "3": "rd", "21": "st", "22": "nd", "23": "rd", "31": "st"};
    var txt_months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

    var f = {
        // Day
        d: function () {
            return pad(f.j(), 2)
        },
        D: function () {
            return f.l().substr(0, 3)
        },
        j: function () {
            return jsdate.getDate()
        },
        l: function () {
            return txt_weekdays[f.w()]
        },
        N: function () {
            return f.w() + 1
        },
        S: function () {
            return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th'
        },
        w: function () {
            return jsdate.getDay()
        }
        ,
        // Week
        W: function () {
            var a = f.z(), b = 364 + f.L() - a;
            var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;
            if (b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b) {
                return 1;
            } else {
                if (a <= 2 && nd >= 4 && a >= (6 - nd)) {
                    nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
                    return date("W", Math.round(nd2.getTime() / 1000));
                } else {
                    return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
                }
            }
        },

        // Month
        F: function () {
            return txt_months[f.n()]
        },
        m: function () {
            return pad(f.n(), 2)
        },
        M: function () {
            return f.F().substr(0, 3)
        },
        n: function () {
            return jsdate.getMonth() + 1
        },
        t: function () {
            var n;
            if ((n = jsdate.getMonth() + 1) == 2) {
                return 28 + f.L();
            } else {
                if (n & 1 && n < 8 || !(n & 1) && n > 7) {
                    return 31;
                } else {
                    return 30;
                }
            }
        },
        //o not supported yet
        Y: function () {
            return jsdate.getFullYear()
        },
        y: function () {
            return (jsdate.getFullYear() + "")
        },

        // Time
        a: function () {
            return jsdate.getHours() > 11 ? "pm" : "am"
        },
        A: function () {
            return f.a().toUpperCase()
        },
        B: function () {
            // peter paul koch:
            var off = (jsdate.getTimezoneOffset() + 60) * 60;
            var theSeconds = (jsdate.getHours() * 3600) + (jsdate.getMinutes() * 60) + jsdate.getSeconds() + off;
            var beat = Math.floor(theSeconds / 86.4);
            if (beat > 1000) beat -= 1000;
            if (beat < 0) beat += 1000;
            if ((String(beat)).length == 1) beat = "00" + beat;
            if ((String(beat)).length == 2) beat = "0" + beat;
            return beat;
        },
        g: function () {
            return jsdate.getHours() % 12 || 12
        },
        G: function () {
            return jsdate.getHours()
        },
        h: function () {
            return pad(f.g(), 2)
        },
        H: function () {
            return pad(jsdate.getHours(), 2)
        },
        i: function () {
            return pad(jsdate.getMinutes(), 2)
        },
        s: function () {
            return pad(jsdate.getSeconds(), 2)
        },
        //u not supported yet

        // Timezone
        //e not supported yet
        //I not supported yet
        O: function () {
            var t = pad(Math.abs(jsdate.getTimezoneOffset() / 60 * 100), 4);
            if (jsdate.getTimezoneOffset() > 0) t = "-" + t; else t = "+" + t;
            return t;
        },
        P: function () {
            var O = f.O();
            return (O.substr(0, 3) + ":" + O.substr(3, 2))
        },
        //T not supported yet
        //Z not supported yet

        // Full Date/Time
        c: function () {
            return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P()
        },
        //r not supported yet
        U: function () {
            return Math.round(jsdate.getTime() / 1000)
        }
    };
    return format.replace(/[\\]?([a-zA-Z])/g, function (t, s) {
        var ret = '';
        if (t != s) {
            ret = s;
        } else if (f[s]) {
            ret = f[s]();
        } else {
            ret = s;
        }
        return ret;
    });
}

/**
 * strtotime()函数
 * strtotime('2012-07-27 12:43:43') OR strtotime('2012-07-27')
 * @return 时间戳
 */
function strtotime(str = '') {
    if (str == '') {
        var _temp = new Date();
        return parseInt(_temp.getTime() / 1000);
    }
    var _arr = str.split(' ');
    var _day = _arr[0].split('-');
    _arr[1] = (_arr[1] == null) ? '0:0:0' : _arr[1];
    var _time = _arr[1].split(':');
    for (var i = _day.length - 1; i >= 0; i--) {
        _day[i] = isNaN(parseInt(_day[i])) ? 0 : parseInt(_day[i]);
    }
    ;
    for (var i = _time.length - 1; i >= 0; i--) {
        _time[i] = isNaN(parseInt(_time[i])) ? 0 : parseInt(_time[i]);
    }
    ;
    var _temp = new Date(_day[0], _day[1] - 1, _day[2], _time[0], _time[1], _time[2]);
    return parseInt(_temp.getTime() / 1000);
}

/**
 * 小数保留默认2位
 */
function returnFloat(value) {
    var value = Math.round(parseFloat(value) * 100) / 100;
    var xsd = value.toString().split(".");
    if (xsd.length == 1) {
        value = value.toString() + ".00";
        return value;
    }
    if (xsd.length > 1) {
        if (xsd[1].length < 2) {
            value = value.toString() + "0";
        }
        return value;
    }
}

/**
 * 加载laoding
 * @param text
 */
const loading = (page, text) => {
    loadDom = page.$loading({
        lock: true,
        text: text,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
    });

    return loadDom;
};
/**
 * 关闭加载层..
 */
const loadingClose = () => {
    if (loadDom != null) {
        loadDom.close();
        loadDom = null;
    }
}

function timest() {
    var tmp = Date.parse(new Date()).toString();
    tmp = tmp.substr(0, 10);
    return tmp;
}

/**
 * 域名信息
 * @returns {{router: *, prefix: *, query: *, domain: *}}
 */
function urlParam() {
    var myURL = new URL(window.document.location.href);
    //get参数
    var url = location.search;
    var theRequest = {};
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        var strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    myURL.query = theRequest;
    return myURL;
}


function confirm(page,delfromData) {
    return new Promise((resolve, reject) => {
        page.$Modal.confirm({
            title: "信息提示",
            content: `<p>${delfromData.title}</p>`,
            loading: true,
            onOk: () => {
                setTimeout(() => {
                    page.$Modal.remove();
                    if (delfromData.success != null) {
                        delfromData.success().then(async res => {
                            resolve(res);
                        }).catch(res => {
                            reject(res)
                        })
                    }
                }, 300);
            },
            onCancel: () => {
                this.$Message.info('取消成功');
            }
        });
    });
}

/**
 * 初始化数据
 * @param data
 * @param def
 * @returns {*}
 */
function resetFields(data, def = {}) {
    var newAr = {};
    for (var i in data) {
        if (def[i] != null) {
            newAr[i] = def[i];
        } else {
            if (typeof (data[i]) == "number") {
                newAr[i] = 0;
            } else {
                newAr[i] = '';
            }
        }
    }
    return newAr;
}

/**
 * 获取图片位置
 * @param img
 * @param index
 */
function imgAr(img, index = -1) {
    if (img == '' || img == null) return null;
    var imgR = img.split(',');
    if (index == -1) return imgR;
    if (imgR.length > index) return imgR[index];
    return null;
}

/**
 * 判断手机号码是否准确
 */
const isPoneAvailable = (tel) => {
    var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    if (!myreg.test(tel)) {
        return false;
    } else {
        return true;
    }
};

/**
 * 倒计时【验证码】
 * @time 倒计时 秒
 * @结束
 */
function CountDowm(time, fe = null) {
    var id = setInterval(() => {
        time--;
        if (fe != null) fe(time, 0);
        if (time <= 0) {
            clearInterval(id);
            fe(0, 1);
        }
    }, 1000);
}

function CountTime(time) {
    var str = "";
    var day = parseInt(time / (3600 * 24));
    var day_yusu = time % (3600 * 24);
    var housr = parseInt(day_yusu / 3600);
    var housr_yusu = day_yusu % 3600;
    var minutes = parseInt(housr_yusu / 60);
    var seconds = housr_yusu % 60;
    if(day > 0){
        str = day + '天';
    } else {
        str = (housr > 9 ? housr : ('0' + housr) ) + ':' ,
        + (minutes > 9 ? minutes : ('0' + minutes) ) + ':' +
        (seconds > 9 ? seconds : ('0' + seconds) );
    }
    return str;
}

function readFile(file) {
    return new Promise(function (resolve, reject) {
        const reader = new FileReader();
        reader.onload = (e) => {
            resolve(e.target.result);
        }
        reader.readAsBinaryString(file);
    });

}


function getTimeVal(time) {
    var reStr = "";
    var hour = 0;
    var minute = 0;
    if (time > 3600) {
        hour = parseInt(time / 3600);
        time = time % 3600;
    }

    if (time > 60) {
        minute = parseInt(time / 60);
        time = time % 60;
    }
    reStr = (hour > 0 ? (hour + '小时') : '')
        + (minute > 0 ? (minute + '分') : '');

    if (reStr == '') reStr = time + "秒";

    return reStr == '' ? '0' : reStr;
}

/**
 * 计算文件大小
 * @param limit
 * @returns {string}
 */
function getFileSize(limit){  // 传参limit为初始值
    var size = "";
    if( limit < 0.1 * 1024 ){ //如果小于0.1KB转化成B
        size = limit.toFixed(2) + "B";
    }else if(limit < 0.1 * 1024 * 1024 ){//如果小于0.1MB转化成KB
        size = (limit / 1024).toFixed(2) + "KB";
    }else if(limit < 0.1 * 1024 * 1024 * 1024){ //如果小于0.1GB转化成MB
        size = (limit / (1024 * 1024)).toFixed(2) + "MB";
    }else{ //其他转化成GB
        size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
    }
    var sizestr = size + "";
    var len = sizestr.indexOf("\.");
    var dec = sizestr.substr(len + 1, 2);
    if(dec == "00"){//当小数点后为00时 去掉小数部分
        return sizestr.substring(0,len) + sizestr.substr(len + 3,2);
    }
    return sizestr;
}



/**
 * 获取数据
 * @param dom
 * @param outHeight
 * @returns {number}
 */
const getPannel = (domid,outHeight = 0) => {
    var height = document.getElementById(domid).offsetHeight;
    if (height == null || height < 400) {
        height = 400;
    }
    return height - outHeight;
}

/**
 * 判断权限
 * @param paths
 * @param value
 */
const checkPermissions = (paths,value) => {
    if(paths.is_system == null) return  false;
    if(paths.is_system == 1) return true;
    for(var i in paths.data) {
        if(paths.data[i].trim() == value.trim()) {
            return  true;
        }
    }
    return  false;
}

/**
 * 自动计算高度 | 宽度
 * @param width 原始
 * @param height 原始
 * @param mWidth 现在 0不参与计算
 * @param mHeight 现在
 */
function getAotuWidth(width,height,mWidth,mHeight = 0) {
    if(mWidth > 0 && mHeight == 0) {
        return (height / width) * mWidth;
    }

    if(mWidth == 0 && mHeight > 0) {
        return (width / height) * mHeight;
    }

    return  0;
}



function accDiv(arg1,arg2){
    var t1=0,t2=0,r1,r2;
    try{t1=arg1.toString().split(".")[1].length}catch(e){}
    try{t2=arg2.toString().split(".")[1].length}catch(e){}
    r1=Number(arg1.toString().replace(".",""))
    r2=Number(arg2.toString().replace(".",""))
    return accMul((r1/r2),pow(10,t2-t1));
}
//乘法
function accMul(arg1,arg2)
{
    var m=0,s1=arg1.toString(),s2=arg2.toString();
    try{m+=s1.split(".")[1].length}catch(e){}
    try{m+=s2.split(".")[1].length}catch(e){}
    return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
}
//加法
function accAdd(arg1,arg2){
    var r1,r2,m;
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
    m=Math.pow(10,Math.max(r1,r2))
    return (arg1*m+arg2*m)/m
}
//减法
function Subtr(arg1,arg2){
    var r1,r2,m,n;
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
    m=Math.pow(10,Math.max(r1,r2));
    n=(r1>=r2)?r1:r2;
    return ((arg1*m-arg2*m)/m).toFixed(n);
}


function RichText(html) {
    if(!isDefine(html)) return '';
    html = html.replace(/\n/g,'<br>');
    return  html;
}

function getFileNameExp(item) {
    let index = item.lastIndexOf('.');
    let exp = item.substr(index+1);
    //xls
    if(['csv','xls','xlsx'].indexOf(exp.toLowerCase()) >= 0) {
        return 'xls';
    }
    //pdf
    if(['pdf'].indexOf(exp.toLowerCase()) >= 0) {
        return 'pdf';
    }
    //word
    if(['docx','doc','wps'].indexOf(exp.toLowerCase()) >= 0) {
        return 'doc';
    }
    //ppt
    if(['ppt','pptx'].indexOf(exp.toLowerCase()) >= 0) {
        return 'ppt';
    }
    //zip
    if(['zip','rar'].indexOf(exp.toLowerCase()) >= 0) {
        return 'zip';
    }

    if(['jpg','jpeg','png'].indexOf(exp.toLowerCase()) >= 0) {
        return 'jpg';
    }

    return  "";
}




function getDuration(time) {
    let second = parseInt(time / 1000);
    second += (time % 1000) > 200 ? 1 : 0;
    return second;
}

/**
 *  格式数据
 *  @filterVal  格式头
 *  @tableData  用来格式的表格数据
 */
function formatJson(filterVal, tableData) {
    return tableData.map(v => {
            return filterVal.map(j => {
                return v[j]
            })
        }
    )
}



export default {
    date: date,//日期(类似PHP)
    strtotime: strtotime,//时间(类似PHP)
    returnFloat: returnFloat,//小数位数
    isDefine: isDefine,//判断是否存在
    timest: timest,//时间戳
    loading: loading,//加载层类
    loadingClose: loadingClose,//关闭加载层
    util: util,
    resetFields: resetFields,//重置ui-element表单
    urlParam: urlParam,//解析URL
    imgAr: imgAr,
    confirm : confirm,//确认操作
    isPoneAvailable: isPoneAvailable,//手机号码检查
    CountDowm: CountDowm,//倒计时
    CountTime  : CountTime,
    readFile: readFile,//读取文件二级制
    getTimeVal: getTimeVal,//时间转化器
    getPannel:getPannel,//中间高度
    checkPermissions : checkPermissions,//权限判断
    getFileSize : getFileSize,//文件大小
    getAotuWidth : getAotuWidth,//自动计算高度-宽度
    accDiv       : accDiv,
    accMul       : accMul,
    accAdd       : accAdd,
    Subtr        : Subtr,
    RichText     : RichText,
    getFileNameExp : getFileNameExp,
    getDuration   : getDuration,
    formatJson   :formatJson
}
